import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

import matplotlib
matplotlib.use('TkAgg')  # 设置后端为TkAgg
# 显示中文，Windows系统
plt.rcParams['font.sans-serif'] = 'SimHei'
# 支持符号
plt.rcParams['axes.unicode_minus'] = False

# 生成示例数据（房屋面积和价格）
np.random.seed(0)
X = np.array([60, 80, 100, 120, 140, 160, 180, 200, 220, 240]).reshape(-1,1)
y = 3000 * X + 100000 + np.random.normal(0, 20000, X.shape)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建线性回归模型
model = LinearRegression()

# 训练模型
model.fit(X_train, y_train)

# 在测试集上进行预测
y_pred = model.predict(X_test)

# 计算均方误差
mse = mean_squared_error(y_test, y_pred)
print(f"均方误差: {mse:.2f}")

# 打印模型参数
print(f"斜率: {model.coef_[0][0]:.2f}")
print(f"截距: {model.intercept_[0]:.2f}")

# 可视化结果
plt.scatter(X, y, color='blue', label='实际数据')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='预测线')
plt.xlabel('房屋面积 (平方米)')
plt.ylabel('房价 (元)')
plt.title('线性回归预测房价')
plt.legend()
plt.show()